var express = require('express')
var newsModel = require('../model/news')
const upload = require('../utils/upload')
var router = express.Router();

// 所有活动 分页 pageIndex 页码，   pageSize:  每页显示多少条数据
router.get('/list',async (req,res)=>{
    const {pageIndex, pageSize} =  req.query;
   let resData = await newsModel.find().skip((pageIndex-1)*pageSize).limit(pageSize);
   // 总共多少页
   let  count = await newsModel.countDocuments();
   let total = Math.ceil(count / pageSize);

   res.send({
        msg:'查询成功',
        code:1,
        total:total,
        data:resData
    })
})

// 添加活动
router.post('/add',upload.single('img_src'), async (req,res)=>{
    const {title,detail} = req.body;
    const fileName = req.file.filename;
    let resData  = await newsModel.create({
        title,
        detail,
        fileName
    })
    res.send({
        msg:'添加成功',
        code:1,
        data:resData
    })

})

// 根据关键词查询活动
router.post('/search',async (req,res)=>{
    const {keyword} = req.body;
    let resData = await newsModel.find({title:{
        $regex: keyword, 
        $options:"$i"
    }})

    res.send({
        msg:'查询成功',
        code:1,
        data:resData
    })
})

 // 删除多条数据   - 让前端 给一个数组， 数组的每一项是一个id ，字段是ids
 router.post('/delete/more', (req,res)=>{
    // 获取到id
    const ids = req.body.ids;  // ['1','2']
    const totalLen = ids.length;
    let curCount=0; 
    ids.forEach(async (id)=>{
        const resData = await newsModel.deleteOne({_id:id});
        if(resData){
            curCount++;
        }
        if(curCount==totalLen){
            // 已经全部删除完毕
            res.send({
                data:'ok',
                code:1,
                msg:'删除成功'
            })
        } 
    })
})


// 删除某一条电影
router.delete('/delete',async (req,res)=>{
    // 获取到id
    const id = req.query.id;
    const resData = await newsModel.deleteOne({_id:id});
    if(resData) {
        res.send({
            code:1,
            data:'ok',
            msg:'删除成功'
        })
    } else {
        res.send({
            code:0,
            data:'ok',
            msg:'删除失败'
        })
    }
})

module.exports = router;